package com.example.myys.viewModel.xsModel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myys.data.entity.DataBean
import com.example.myys.data.repository.BookRepository
import com.example.myys.ui.Resource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class XsSjViewModel:ViewModel() {
    val bookRepository = BookRepository()
    //书城推荐
    private val _scTjState: MutableStateFlow<Resource<List<DataBean>>>
            = MutableStateFlow(value = Resource.Loading())

    val scTjState: StateFlow<Resource<List<DataBean>>>
        get() = _scTjState
    //书架
    private val _sjState: MutableStateFlow<Resource<List<DataBean>>>
            = MutableStateFlow(value = Resource.Loading())

    val sjState: StateFlow<Resource<List<DataBean>>>
        get() = _sjState

    fun getXsWbDate() {
        viewModelScope.launch(Dispatchers.IO){
            val bookList = bookRepository.getBookRecommend()
            if (bookList == null) {
                _scTjState.value=Resource.Error()
            }else{
                _scTjState.value=Resource.Success(bookList)
            }
        }
    }
    fun getSearchBook(keyword:String) {
        _scTjState.value=Resource.Loading()
        viewModelScope.launch(Dispatchers.IO){
            val bookList = bookRepository.getBookByKeyword(keyword)
            if (bookList == null) {
                _scTjState.value=Resource.Error()
            }else{
                _scTjState.value=Resource.Success(bookList)
            }
        }
    }
    fun getBookShelf(){
        _sjState.value=Resource.Loading()
        viewModelScope.launch(Dispatchers.IO) {
            val sjList = bookRepository.getBookShelf()
            if(sjList==null){
                _sjState.value=Resource.Error()
            }else{
                _sjState.value= Resource.Success(sjList)
            }

        }
    }
    fun addBookShelf(DataBean: DataBean){
        viewModelScope.launch(Dispatchers.IO) {
            bookRepository.addBookShelf(DataBean)
            getBookShelf()
        }
    }
    fun deleteBookShelf(dataBean: DataBean) {
        viewModelScope.launch(Dispatchers.IO) {
            bookRepository.deleteShelf(dataBean)
            getBookShelf()
        }
    }
    init {
        getBookShelf()
        getXsWbDate()
    }

}